package com.cn.test.xuanhttplibrary.okhttp.builder;

import android.text.TextUtils;
import android.util.Log;

import com.cn.test.base.GlobalApp;
import com.cn.test.util.JsonUitl;
import com.cn.test.util.PrefShare;
import com.cn.test.xuanhttplibrary.okhttp.HttpUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author Administrator
 * @time 2017/3/30 0:11
 * @des ${TODO}
 */

public class PostBuilder extends BaseBuilder {

    @Override
    public PostBuilder url(String url) {
        if (!TextUtils.isEmpty(url)) {
            this.url = url;
        }
        return this;
    }

    @Override
    public PostBuilder tag(Object tag) {
        this.tag = tag;
        return this;
    }

    /**
     * 给所有  需要 token userid接口调添加secret,
     */
    public PostBuilder addSecret() {
        String token = PrefShare.getInstance(GlobalApp.getAppContext()).getString("token");
        String userId = PrefShare.getInstance(GlobalApp.getAppContext()).getString("userId");
        params.put("token", token);
        params.put("userid", userId);
        return this;
    }


    @Override
    public PostCall build() {
        Request.Builder RequestBuilderUrl = new Request.Builder().url(this.url);
        //添加请求头
        if (headers != null) {
            for (String key : headers.keySet()) {
                RequestBuilderUrl.addHeader(key, headers.get(key));
            }
        }
        build = RequestBuilderUrl.post(getJsonRequestBody())
                .build();
        // 如果tag不为空，进入队列管理
        PostCall call = new PostCall();
        if (httpUtils != null && tag != null) {
            Map<Object, List<Object>> mCalls = httpUtils.getCalls();
            if (tag != null) {
                List<Object> list = mCalls.get(tag);
                if (list == null) {
                    list = new ArrayList<>();
                    mCalls.put(tag, list);
                }
                list.add(call);
            }
        }
        return call;
    }

    /**
     * body 以json形式转递
     *
     * @return
     */
    private RequestBody getJsonRequestBody() {
        //下面的操作是  打印传递的数据   方便测试
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        sb.append("?");
        if (params != null) {
            for (String key : params.keySet()) {
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
        }
        sb = sb.deleteCharAt(sb.length() - 1); // 去掉后面的&
        Log.i(HttpUtils.TAG, "post网络请求参数：" + sb.toString());

        String JsonString = JsonUitl.objectToString(params);
        //创建body
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JsonString);
        return requestBody;
    }

    /**
     * builder.add(key, params.get(key));  以key value 形式传递
     *
     * @param builder
     * @return
     */
    private RequestBody appenParams(FormBody.Builder builder) {
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        sb.append("?");
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
        }
        sb = sb.deleteCharAt(sb.length() - 1); // 去掉后面的&
        Log.i(HttpUtils.TAG, "post网络请求参数：" + sb.toString());
        return builder.build();
    }


    @Override
    public PostBuilder params(String k, String v) {
        // this.url = this.url+k+"="+v;
        if (params == null) {
            params = new LinkedHashMap<>();
        }
        params.put(k, v);
        return this;
    }

    /**
     * 设置参数
     *
     * @param params
     * @return
     */
    public PostBuilder params(Map<String, String> params) {
        // 所有接口都需要time与secret参数
        /*
        目前只有微信取现(VX_TRANSFER_PAY)使用了post的方式，且在WXEntryActivity内已经处理好了，此处不再处理
        如后续还有其他接口使用post的请求方式，就需要在这里拼接了，可参考GetBuilder
         */
        this.params = params;
        return this;
    }

    /**
     * 设置请求  heard
     *
     * @param headers
     * @return
     */
    public PostBuilder headers(Map<String, String> headers) {
        // 所有接口都需要time与secret参数
        /*
        目前只有微信取现(VX_TRANSFER_PAY)使用了post的方式，且在WXEntryActivity内已经处理好了，此处不再处理
        如后续还有其他接口使用post的请求方式，就需要在这里拼接了，可参考GetBuilder
         */
        this.headers = headers;
        return this;
    }


    public PostBuilder(HttpUtils httpUtils) {
        this.httpUtils = httpUtils;
    }

    private HttpUtils httpUtils;

    public class PostCall extends BaseCall {
        private Call call;

        @Override
        public Call execute(Callback callback) {
            Call call = super.execute(callback);
            this.call = call;
            return call;
        }

        Call getCall() {
            return call;
        }
    }
}
